import React, { useState } from "react";
import fishTokenContract from "../fishToken";
import web3 from "../web3";

const BuyTokens = () => {
    const [ethAmount, setEthAmount] = useState("");
    const [message, setMessage] = useState("");

    const buyTokens = async () => {
        try {
            const accounts = await web3.eth.getAccounts();
            if (accounts.length === 0) {
                alert("请连接钱包");
                return;
            }

            const tx = await fishTokenContract.methods.buyTokens().send({
                from: accounts[0],
                value: web3.utils.toWei(ethAmount, "ether"),
            });

            setMessage(`交易成功！交易哈希: ${tx.transactionHash}`);
        } catch (error) {
            setMessage(`交易失败: ${error.message}`);
        }
    };

    return (
        <div>
            <h2>购买鱼币</h2>
            <input
                type="text"
                placeholder="输入ETH金额"
                value={ethAmount}
                onChange={(e) => setEthAmount(e.target.value)}
            />
            <button onClick={buyTokens}>购买</button>
            {message && <p>{message}</p>}
        </div>
    );
};

export default BuyTokens;

